import Socket from '@/websocket/index';
import { useEquipmentInfoStore } from '@/stores/equipment-info-store';
export default () => {
    let wbSocket;
    const store = useEquipmentInfoStore();
    const closeWebsocket = () => {
        wbSocket && wbSocket.destroy();
    };
    const recevierMsg = (e) => {
        console.log('Received message:', e.data);  // 调试输出
        try {
            // 如果接收到的是 "ping"，回复 "pong"
            if (e.data.includes("ping")) {
                //wbSocket.send('pong');  // 回复 "pong"
                return;
            }

            const data = JSON.parse(e.data);
            store.setEquipmentInfo(data);
        } catch (error) {
            console.error('Error parsing JSON:', error);
        }
    };
    const initSokect = () => {
        if (location.href.indexOf('/login/') > -1)
            return;
        const token = localStorage.getItem('token');
        wbSocket = new Socket({ url: `ws://127.0.0.1:8081/login?token=${token}`, messageCb: recevierMsg });
    };
    initSokect();
    window.addEventListener('unload', () => {
        wbSocket && wbSocket.destroy();
    });
    return {
        closeWebsocket,
        initSokect
    };
};
